package com.etrans.web.gps.business.base.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.base.domain.SimCardVO;
import com.etrans.web.gps.business.base.domain.Terminal;
import com.etrans.web.gps.business.base.service.SimCardService;
import com.etrans.web.gps.business.base.service.TerminalService;
import com.etrans.web.gps.business.base.service.UnitService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageResultVo;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.common.page.ResultContans;
import com.etrans.web.gps.util.grid.FlexiGridUtil;


/**
 * 终端信息
 * @author yin
 * 2017-07-04
 */
@Controller
@RequestMapping("/base/terminal/*")
public class TerminalController extends BaseController{
	@Autowired
	private TerminalService terminalService;
	
	@Autowired
	private SimCardService  simCardService;
	
	@Autowired
	private UnitService unitService;
	
	// 查询所有终端
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "loadAllTerminals.html")
	@ResponseBody
	public PageVo loadAllTerminals(@RequestParam String paramsGrid) {
		PageVo page = new PageVo();		
		Map<String, Object> paramMap =  FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		List rows = terminalService.queryAllTerminals(paramMap);	
		page.setRows(rows);
		page.setPage((int)paramMap.get("page"));
		page.setTotal(terminalService.queryTerminalCount(paramMap));

		return page;
	}
	
	
	@RequestMapping(value = "initTerminalForm.html")
	@ResponseBody
	public ModelAndView initTerminalForm(@RequestParam  Model model) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("action", "insert");
		mav.addObject("terminal", new Terminal());
		mav.setViewName("views/base/terminal/addTerminalForm");
		return mav;	
	}
	
	@RequestMapping(value = "initUpdateTerminalForm.html")
	@ResponseBody
	public ModelAndView initUpdateTerminalForm(@RequestParam  Integer terminalId) {
		ModelAndView mav = new ModelAndView();
		Terminal terminal = terminalService.queryTerminalById(terminalId);
		terminal.setId(terminalId);
		// 存储旧的sim卡ID
		terminal.setOldSimId(terminal.getSimId());
		terminal.setOldCommNo(terminal.getCommNo());
		terminal.setOldTerminalKindId(terminal.getTerminalKindId());
		terminal.setOldUseFlag(terminal.getUseFlag());
		mav.addObject("terminal", terminal);
		mav.addObject("action", "update");
		mav.setViewName("views/base/terminal/addTerminalForm");
		return mav;	
	}
	
	@RequestMapping(value = "updateTerminal.html")
	@ResponseBody
	public Terminal updateTerminal(@RequestParam  Integer terminalId) {
		try {
			// 查找相应的终端
			Terminal terminal = terminalService.queryTerminalById(terminalId);
			terminal.setId(terminalId);
			// 存储旧的sim卡ID
			terminal.setOldSimId(terminal.getSimId());
			terminal.setOldCommNo(terminal.getCommNo());
			terminal.setOldTerminalKindId(terminal.getTerminalKindId());
			terminal.setOldUseFlag(terminal.getUseFlag());
			return terminal;
		} catch (Exception e) {
			//logger.error("", e);
			e.printStackTrace();
			return null;
		}
	}
	
	@RequestMapping(value = "saveTerminal.html")
	@ResponseBody
	public Map saveTerminal(@RequestParam  String action,Terminal terminal) {
		Map result = new HashMap();
		try {
			// 保证通信号唯一性
			HashMap<String, Object> param = new HashMap<String, Object>();
			if(terminal.getOldCommNo()!=null&&terminal.getOldCommNo()!=""){
				param.put("COMMNO", terminal.getOldCommNo());
			}else{
				param.put("COMMNO", terminal.getCommNo());
			}
			if ("update".equals(action)) {
				param.put("ID", terminal.getId());
			} 
			int Count = terminalService.queryCountByCOMMNO(param);
			if (Count == 0) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if ("insert".equals(action)) {
					// 默认是停用
					terminal.setUseFlag(0);
					// 直接保存
					terminalService.saveTerminal(terminal);
				}

				if ("update".equals(action)) {
					if(terminal.getOldUseFlag()==0){
						param.put("COMMNO", terminal.getCommNo());
					}else{
						terminal.setCommNo(terminal.getOldCommNo());
					}	
					if(terminal.getTerminalKindId() == null){
						terminal.setTerminalKindId(terminal.getOldTerminalKindId());
					}
					terminalService.updateTerminal(terminal);
				}
				result.put("code", Constant.RETURN_OK_CODE);
			} else {
				// 已经重复
				result.put("code", Constant.RETURN_Repent_CODE);
			}
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("", e);
			result.put("code", Constant.RETURN_Repent_CODE);
			result.put("msg", "保存失败!");
		}
		return result;
	}
	
	// 删除终端信息
	@RequestMapping(value = "delTerminal.html")
	@ResponseBody
	public Map<String,Object> delTerminal(@RequestParam  String TerminalIds) {
		Map<String, Object> result = new HashMap<>();
		try {
			if (TerminalIds != null && !"".equals(TerminalIds)) {
				String[] ArrayvehicleId = TerminalIds.split(",");
				Integer terminalID;
				int IFUserFlag = 0;
				for (String perID : ArrayvehicleId) {
					terminalID = Integer.parseInt(perID);
					Integer userFlag;
					Terminal terminalTerminal = terminalService
							.queryTerminalById(terminalID);
					userFlag = terminalTerminal.getUseFlag();
					if (userFlag == null) {
						userFlag = 0;
					}
					// 如果是开户状态，不能删除信息
					if (userFlag.equals(0)) {
						terminalService.deleteTerminalByID(terminalID);
					} else {
						IFUserFlag = 1;
					}
				}
				if (IFUserFlag == 0) {
					result.put("code", Constant.RETURN_OK_CODE);
				} else {
					result.put("code", Constant.RETURN_Repent_CODE);
				}
			}
		} catch (Exception e) {
			//logger.error("", e);
			e.printStackTrace();
			result.put("code", Constant.RETURN_ERROR_CODE);
			result.put("msg", "删除失败!");
		}
		return result;
	}
	
	// 查询所有终端类型树
	@RequestMapping(value = "loadAllTerminalKindTrees.html")
	@ResponseBody
	public List<HashMap<String, Object>> loadAllTerminalKindTrees() {
		try {
			List rows = terminalService.loadAllTerminalKindTrees();
			return rows;
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("", e);
			return new ArrayList();
		}
		
		
	}
		
	/**
	 * 导出终端信息
	 * @param response
	 * @param paramsGrid
	 * @param StartPage
	 * @param EndPage
	 */
	@RequestMapping(value = "exportTerminals.html")
	public void exportTerminals(@RequestParam HttpServletRequest request,HttpServletResponse response,String paramsGrid, String colModel, String title,String StartPage,String EndPage,String pagesize) {
		Map<String, Object> paramMap=getReqParameters();
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		List<Terminal> list = terminalService.queryTerminalExportList(paramMap);			
		List<HashMap<String, String>> rows = new ArrayList<HashMap<String, String>>();
		
		int start=Integer.valueOf(Integer.valueOf(StartPage)-1)*Integer.valueOf(pagesize);
		int end=Integer.valueOf(EndPage)*Integer.valueOf(pagesize);
		if(end>(list.size()-1)){
			end=list.size();
		}
		for(int i=start;i<end;i++){
			HashMap<String, String> map = new HashMap<String, String>();				
			
			Terminal obj=(Terminal)list.get(i);
			map.put("workUnitName", obj.getWorkUnitName()==null ? "" : obj.getWorkUnitName());
			map.put("commNo", obj.getCommNo()==null ? "" : obj.getCommNo());
			map.put("simPhoneNo", obj.getSimPhoneNo()==null ? "" : obj.getSimPhoneNo());
			map.put("terminalKindName", obj.getTerminalKindName()==null ? "" : obj.getTerminalKindName());
			map.put("batchNo", obj.getBatchNo()==null ? "" : obj.getBatchNo());
			map.put("platformTerminalId", obj.getPlatformTerminalId()==null ? "" : obj.getPlatformTerminalId());
			map.put("manuFacturerTerminalId", obj.getManuFacturerTerminalId()==null ? "" : obj.getManuFacturerTerminalId());
			map.put("modelType", obj.getModelType()==null ? "" : obj.getModelType());
			map.put("signCode", obj.getSignCode()==null ? "" : obj.getSignCode());
			map.put("useFlagStr", obj.getUseFlagStr()==null ? "" : obj.getUseFlagStr());						
			rows.add(map);
		}
		
		int index=-1;
		List rowsList = new ArrayList<>();
		rowsList.add(rows);
		exportExl(request, response,title, removeHeadName(colModelList,index,-1),rowsList,null);
	}
	
	@RequestMapping(value = "checkIfExistCOMMNO.html")
	@ResponseBody
	public Map<String, Object> checkIfExistCOMMNO(String COMMNO) {
		Map<String, Object> map = new HashMap<>();
		HashMap<String, Object> parms = new HashMap<String, Object>();
		parms.put("COMMNO", COMMNO);
		int Count = terminalService.queryCountByCOMMNO(parms);
		if (Count == 0) {
			map.put("code", ResultContans.RETURN_OK_CODE.getCode());
		}
		else {
			map.put("code", ResultContans.RETURN_REPENT_CODE.getCode());
		}
		return map;
	}
	
	
	@RequestMapping(value = "saveTerminalSimple.html")
	@ResponseBody
	public PageResultVo saveTerminalSimple(@RequestParam 
			String UnitID, String SimNo, String ComNo, String TerminalTypeID) {
		PageResultVo resultVo = new PageResultVo();
		try {

			// 添加终端信息
			Terminal terminal = new Terminal();
			terminal.setTerminalKindId(Integer.parseInt(TerminalTypeID));
			terminal.setCommNo(ComNo);
			terminal.setWorkUnitId(Integer.parseInt(UnitID));
			// 判断sim卡有没有存在，不存在就添加
			HashMap<String, Object> parms = new HashMap<String, Object>();
			parms.put("PhoneNO", SimNo);
			int Count = simCardService.queryCountByPhoneNO(parms);
			if (Count == 0) {
				// 首先添加sim卡
				SimCardVO simCardVO = new SimCardVO();
				simCardVO.setPhoneNO(SimNo);
				simCardVO.setCode(SimNo);
				simCardVO.setWorkUnitId(Integer.parseInt(UnitID));
				// 未使用
				simCardVO.setIsInUse(0);
				simCardService.saveSimCard(simCardVO);
				terminal.setSimId(simCardVO.getId());

			} else {
				Integer simCardID = simCardService.queryIDByPhoneNO(parms);
				terminal.setSimId(simCardID);
			}
			// 停用
			terminal.setUseFlag(0);
			terminalService.saveTerminal(terminal);
			resultVo.setCode(terminal.getId());
		} catch (Exception e) {
			//logger.error("", e);
			resultVo.setCode(ResultContans.RETURN_ERROR_CODE.getCode());
			resultVo.setMsg("保存失败!");
		}
		return resultVo;
	}
}
